package cn.iocoder.yudao.framework.excel.core.util;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;

import java.util.List;
import java.util.Map;
import java.util.Optional;

public class ColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {

    private static final int MAX_COLUMN_WIDTH = 255;

    private Map<String, List<TableHeaderVO>> sheetHeaderMap;

    public ColumnWidthStyleStrategy(Map<String, List<TableHeaderVO>> sheetHeaderMap) {
        this.sheetHeaderMap = sheetHeaderMap;
    }

    @Override
    protected void setColumnWidth(
            WriteSheetHolder writeSheetHolder,
            List<WriteCellData<?>> cellDataList,
            Cell cell,
            Head head,
            Integer relativeRowIndex,
            Boolean isHead) {
        final int rowIndex = cell.getRowIndex();
// 只在第一行设置列宽即可
        if (rowIndex != 0) {
            return;
        }
        final List<TableHeaderVO> list = sheetHeaderMap.get(writeSheetHolder.getSheetName());

        Integer columnWidth = dataLength(list, cell);
        if (columnWidth < 0) {
            return;
        }
        if (columnWidth > MAX_COLUMN_WIDTH) {
            columnWidth = MAX_COLUMN_WIDTH;
        }
        Integer maxColumnWidth = 1;
        if (columnWidth > maxColumnWidth) {
            writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
        }
    }

    // 根据 cell 中写入的内容，查找该列配置的表头列宽
    private Integer dataLength(List<TableHeaderVO> list, Cell cell) {

        final String cellValue = cell.getStringCellValue();

        final Optional<TableHeaderVO> headerOptional =
                list.stream().filter(k -> cellValue.equals(k.getLabel())).findFirst();
        return headerOptional.map(tableHeaderVO -> tableHeaderVO.getWidth().intValue()).orElse(1);
    }
}
